package org.brisling.common.util;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.brisling.base.domain.inf.BaseDomainInf;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class StringUtil {
	
	
	private static StringUtil su = null;
	
	private StringUtil(){};
	
	public static StringUtil getInstance(){
		if(su==null){
			su = new StringUtil();
		}
		return su;
	}
	
	public static HashMap<String,Object> splitRequestStr2Map(String inData){
		
		String splitChar = "&";
		HashMap<String,Object> retMap = new HashMap<String,Object>();
		
		if(inData!=null){
			if(splitChar!=null){
				String[] _list = inData.split(splitChar); 
				
				if(_list!=null&&_list.length>0){
					for(int i =0;i<_list.length;i++){
						String[] _nameValue = _list[i].split("=");
						if(_nameValue!=null&&_nameValue.length>1){
							retMap.put(_nameValue[0], _nameValue[1]);
						}
					}
				}
			}
		}
		return retMap;
	}
	
	public static List<Long> splitStr2Long(String inStr,String splitStr){
		
		List<Long> retList = new ArrayList<Long>();
		
		if(inStr!=null){
			if(splitStr!=null){
				String[] _s = inStr.split(splitStr);
				if(_s!=null&&_s.length>0){
					for(int i=0;i<_s.length;i++){
						retList.add(LongUtil.getLongValue(_s[i], null));
					}
				}
			}
		}
		
		return retList;
		
	}
	
	/**
	 * 将字符串集合转化为Long数据集合
	 * @param strList
	 * @return
	 */
	public static List<String> getStringList(List<Long> longList){
		
		List<String> strList = new ArrayList<String>();
		if((longList!=null) && (longList.size()>0)){
			for(int i=0;i<longList.size();i++){
				strList.add(longList.get(i).toString());
			}
		}
		return strList;
	}
	
	/**
	 * 获取实体类id集合
	 * @param strList
	 * @return List<Long>
	 */
	public static List<String> getStringIdList(List<? extends BaseDomainInf> domains){
		
		List<String> strList = new ArrayList<String>();
		if((domains!=null) && (domains.size()>0)){
			for(int i=0;i<domains.size();i++){
				strList.add(domains.get(i).getId().toString());
			}
		}
		return strList;
	}
	
	/**
	 * 根据sql定义，用valueMap中的值替换查询条件
	 * @param sql	动态sql定义
	 * @param valueMap	查询字段名称及值集合
	 * @param orderMap  查询排序字段名称及排序方式集合
	 * @return	使用参数格式化后的查询语句
	 */
	public static String getSqlString(String sql,HashMap<String,String> valueMap,LinkedHashMap<String,String> orderMap){
		return null;
	}
	
	/*
	 * 字段编码
	 */
	private static String VALCODE = "\\$F\\{(";
	
	private static String ENDCODE = ")\\}";
	public  static String formatSqlValue(String sql,HashMap<String,String> val){
		
		
		
		String template = "$F{cat} really needs some $F{beverage}."; 
		
		String _sql = sql==null?template:sql;
		
		if(_sql!=null || _sql.trim().length()>0){
			_sql = _sql.trim();
			
			 //匹配类似velocity规则的字符串 
			
		    
		    if(val!=null && val.size()>0){
		    	
		    	for(String _f:val.keySet()){
				    //生成匹配模式的正则表达式 		
				    Pattern pattern = Pattern.compile(VALCODE + _f + ENDCODE); 
				    Matcher matcher = pattern.matcher(_sql); 
		
				    //两个方法：appendReplacement, appendTail 
				    
				    while(matcher.find()) { 
				    	_sql = matcher.replaceAll(val.get(matcher.group(1)));				        
				    } 
//				    matcher.appendTail(ret); 
		
				    //out: Garfield really needs some coffee. 
				    System.out.println(_sql.toString());
		    	}
		    }
			
		}
		
		return _sql;
	}
	/**
	 * 获取拼音码首拼字母
	 * @param inStr
	 * @return
	 */
	public static String getPinyinCodeFirstSpell(String inStr){
		
		String ret = null;
		if(inStr !=null){
			ret = converterToFirstSpell(inStr);
		}
		
		return ret;
	}
	
	/**    
     * 汉字转换为汉语拼音首字母，英文字符不变    
     * @param chines 汉字    
     * @return 拼音 
     */        
    private static String converterToFirstSpell(String chines){                
         String pinyinName = "";     
           
         //转化为字符  
         char[] nameChar = chines.toCharArray();  
//         for(int i=0;i<nameChar.length;i++){  
//           System.out.println(nameChar[i]);  
//         }  
           
         //汉语拼音格式输出类     
         HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();  
           
         //输出设置,大小写,音标方式等     
         defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);         
         defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);         
           
         for (int i = 0; i < nameChar.length; i++) {         
             //如果是中文  
             if (nameChar[i] > 128) {  
                try {         
                     pinyinName +=   
                           PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0].charAt(0);         
                 } catch (BadHanyuPinyinOutputFormatCombination e) {         
                     e.printStackTrace();         
                 }         
             }else{//为英文字符      
                 pinyinName += nameChar[i];         
             }         
         }         
        return pinyinName;         
     }    
    
    
    //freemarker 模板配置
    private static Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
    
    /**
     * 格式化sql语句
     * @param inSql	sql模板
     * @param param 格式化参数值
     * @return
     */
    public static String formatSql(String inSql,Map<String,Object> param){
    	
    	if(inSql == null || param==null){
    		return null;
    	}
    	
    	Template template = null;
        StringWriter writer = new StringWriter();
        
        try {
			template = new Template("",inSql,cfg);
			template.process(param, writer); 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
    	return writer.toString();
    }
    
    /**
     * 格式化sql语句
     * @param inSql	sql模板
     * @param param 格式化参数值
     * @return
     */
    public static String formatSqlByString(String inSql,Map<String,String> param){
    	
    	if(inSql == null || param==null){
    		return null;
    	}
    	
    	Template template = null;
        StringWriter writer = new StringWriter();
        
        try {
			template = new Template("",inSql,cfg);
			template.process(param, writer); 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
    	return writer.toString();
    }
    
    /**
     * 格式化sql语句
     * @param inSql	sql模板
     * @param param 格式化参数值
     * @return
     */
    public static String formatSql(Map<String,String> param,String inSql){
    	
    	if(inSql == null || param==null){
    		return null;
    	}
    	
    	Template template = null;
        StringWriter writer = new StringWriter();
        
        try {
			template = new Template("",inSql,cfg);
			template.process(param, writer); 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
    	return writer.toString();
    }
    
    /**
     * 获取随机长度的字符串
     * @param length
     * @return
     */
    public static String getRandomString(int length) {   
        StringBuffer buffer = new StringBuffer("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");   
        StringBuffer sb = new StringBuffer();   
        Random random = new Random();   
        int range = buffer.length();   
        for (int i = 0; i < length; i ++) {   
            sb.append(buffer.charAt(random.nextInt(range)));   
        }   
        return sb.toString();   
    }  

}
